package cn.bugstack.trigger.listener;

import cn.bugstack.api.dto.TeamRefundSuccessRequestDTO;
import cn.bugstack.domain.auth.service.WechatMessageService;
import cn.bugstack.domain.order.adapter.repository.IOrderRepository;
import cn.bugstack.domain.order.model.entity.OrderEntity;
import cn.bugstack.domain.order.service.IOrderService;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 营销退单成功消息
 */
@Slf4j
@Component
public class RefundSuccessTopicListener {

    @Resource
    private IOrderService orderService;
    @Resource
    private WechatMessageService wechatMessageService;

    /**
     * 指定消费队列
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "${spring.rabbitmq.config.consumer.topic_team_refund.queue}"),
                    exchange = @Exchange(value = "${spring.rabbitmq.config.consumer.topic_team_refund.exchange}", type = ExchangeTypes.TOPIC),
                    key = "${spring.rabbitmq.config.consumer.topic_team_refund.routing_key}"
            )
    )
    public void listener(String message) {
        try {
            log.info("退单回调，发起退款 {}", message);
            TeamRefundSuccessRequestDTO requestDTO = JSON.parseObject(message, TeamRefundSuccessRequestDTO.class);
            String type = requestDTO.getType();
            if ("paid_unformed".equals(type) || "paid_formed".equals(type)) {
                // 在拼团的订单状态退单后  支付宝退款和更新状态
                boolean refundSuccess = orderService.refundPayOrder(requestDTO.getUserId(), requestDTO.getOutTradeNo());
                if (refundSuccess) {
                    log.info("拼团回调，退单完成，退款成功 {}", message);

                    try {
                        wechatMessageService.sendRefundMessage(
                                requestDTO.getUserId(),
                                requestDTO.getOutTradeNo(),
                                // TODO 写死
                                "80"
                        );
                    } catch (Exception e) {
                        log.error("发送微信退款消息失败 userId:{}, orderNo:{}",
                                requestDTO.getUserId(), requestDTO.getOutTradeNo(), e);
                        // 微信消息发送失败不影响主流程
                    }
                } else {
                    log.info("拼团回调，退单完成，退款失败 {}", message);
                }
            }
        } catch (AlipayApiException ex) {
            throw new RuntimeException(ex);
        } catch (Exception e) {
            log.error("拼团回调，退单完成，退款失败 {}", message, e);
            throw e;
        }
    }

}
